#!/usr/bin/env python
#!coding=utf-8
'''
Copyright (c) 2012, Chen MuSheng.
License: MIT (see LICENSE for details)
'''
from bottle import BaseTemplate
from  inspect  import currentframe,getouterframes

__all__=['BottleStePyproxy']
__author__ = 'Chen MuSheng'
__version__ = '0.0.1'
__license__ = 'MIT'

class BottleStePyProxy(object):

    def __setitem__(self,name,value):
        self.__dict__[name]=value

    def __getattr__(self,name):
        return self.__dict__[name]

    @classmethod
    def setup(cls,callback,name=''):
        assert cls.__name__ in BaseTemplate.defaults,'bottle_ste_pyproxy must be install.'
        if not name:
            name=callback.__name__
        BaseTemplate.defaults['py'][name]=callback

    @classmethod
    def install(cls):
        BaseTemplate.defaults[cls.__name__]=cls()
        BaseTemplate.defaults['py']=BaseTemplate.defaults[cls.__name__]

    @classmethod
    def uninstall(cls):
        if 'py' in BaseTemplate.defaults:
            BaseTemplate.defaults.remove('py')
        if cls.__name__ in BaseTemplate.defaults:
            BaseTemplate.defaults.remove(cls.__name__)

    def multiline(self):
        pass

    def getmultiline(self):
        cf=currentframe()
        of=getouterframes(cf)[1]
        return of[0].f_locals['_stdout'].pop()

BottleStePyProxy.install()
